package me.trofoto.romeo;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import me.trofoto.romeo.bean.User;
import me.trofoto.romeo.bean.UserInSession;
import me.trofoto.romeo.dao.UserDao;

/**
 * 不需要过滤的url放这里
 */
@Controller
@RequestMapping("/guest")
public class GuestController {

	private static final String VIEW_PREFIX = "guest/";

	@Resource
	private UserDao userDao;

	@GetMapping("/login")
	public String loginEntry(Model model) {
		List<User> users = userDao.getAllUsers();
		model.addAttribute("users", users);
		return VIEW_PREFIX + "login";
	}

	@PostMapping("/login")
	public String login(@RequestParam Integer userId, HttpServletResponse response, HttpSession session) {
		User user = userDao.getById(userId);
		if (null == user) {
			throw new IllegalArgumentException("未找到id为" + userId + "的用户");
		}
		session.setAttribute("user", new UserInSession(user.getId(), user.getNickname()));
		return "redirect:/";
	}
	
	@PostMapping("/logout")
	public String logout(HttpSession session, Model model) {
		session.removeAttribute("user");
		return loginEntry(model);
	}

	@GetMapping("/register")
	public String registerEntry() {
		return VIEW_PREFIX + "register";
	}
	
	@PostMapping("/register")
	public String registerEntry(User user, HttpSession session, Model model) {
		int userId = userDao.insert(user);
		session.setAttribute("user", new UserInSession(userId, user.getNickname()));
		return "redirect:/";
	}
	
}
